package com.laxcen.basiclib.core.mqtt;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;

import com.laxcen.basiclib.BaseApp;
import com.laxcen.basiclib.BaseConst;
import com.laxcen.basiclib.core.mqtt.core.MqttAndroidClient;
import com.laxcen.basiclib.core.task.TaskManager;
import com.laxcen.basiclib.utils.LogUtil;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 *  mqtt 管理器
 */
public class MqttManager {

    private final   String   TAG  = MqttManager.class.getSimpleName();
    private static MqttAndroidClient mqttAndroidClient;
    private MqttConnectOptions mMqttConnectOptions;
    private   String   HOST  = BaseConst.mqttHost;//服务器地址（协议+地址+端口号）
    private   String   USERNAME  = BaseConst.mqttUsername;//用户名
    private   String   PASSWORD  = BaseConst.mqttPassword;//密码
    private static  String  WILL_TOPIC  = "will_topic";//遗嘱
    @SuppressLint("MissingPermission")
    private    String CLIENTID = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
            ? Build.getSerial() : Build.SERIAL;//客户端ID，一般以客户端唯一标识符表示，这里用设备序列号表示
    private static MqttManager mqttManager;
    public static MqttManager getInstance(){
        if(mqttManager==null){
            synchronized (MqttManager.class){
                if(mqttManager==null){
                    mqttManager = new MqttManager();
                    mqttManager.init();
                }
            }
        }
        return mqttManager;
    }

    private void init(){
        String serverURI = HOST; //服务器地址（协议+地址+端口号）
        mqttAndroidClient = new MqttAndroidClient(BaseApp.getApp(), serverURI, CLIENTID);
        mqttAndroidClient.setCallback(mqttCallback); //设置监听订阅消息的回调
        mMqttConnectOptions = new MqttConnectOptions();
        mMqttConnectOptions.setCleanSession(true); //设置是否清除缓存
        mMqttConnectOptions.setConnectionTimeout(10); //设置超时时间，单位：秒
        mMqttConnectOptions.setKeepAliveInterval(20); //设置心跳包发送间隔，单位：秒
        mMqttConnectOptions.setUserName(USERNAME); //设置用户名
        mMqttConnectOptions.setPassword(PASSWORD.toCharArray()); //设置密码


        // last will message
        boolean doConnect = true;
        String message = "{\"terminal_uid\":\"" + CLIENTID + "\"}";
        String topic = WILL_TOPIC;
        Integer qos = 2;
        Boolean retained = false;
        if ((!message.equals("")) || (!topic.equals(""))) {
            // 最后的遗嘱
            try {
                mMqttConnectOptions.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
            } catch (Exception e) {
                Log.i(TAG, "Exception Occured", e);
                doConnect = false;
                iMqttActionListener.onFailure(null, e);
            }
        }
        if (doConnect) {
            doClientConnection();
        }
    }


    private void reconnect(int delay){
        TaskManager.getInstance().exec(() -> {
            doClientConnection();
        },delay);
    }
    /**
     * 连接MQTT服务器
     */
    private void doClientConnection() {
        if (!mqttAndroidClient.isConnected() && isConnectIsNomarl()) {
            try {
                mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断网络是否连接
     */
    private boolean isConnectIsNomarl() {
        ConnectivityManager connectivityManager = (ConnectivityManager) BaseApp.getApp()
                .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            Log.i(TAG, "当前网络名称：" + name);
            return true;
        } else {
            Log.i(TAG, "没有可用网络");
            if(mqttMessageCallback!=null){
                mqttMessageCallback.onAction(ActionType.NO_NETWORK,"没有可用网络");
            }
            /*没有可用网络的时候，延迟3秒再尝试重连*/
            reconnect(3000);
            return false;
        }
    }

    //MQTT是否连接成功的监听
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken arg0) {
            Log.i(TAG, "连接成功 ");
            if(mqttMessageCallback!=null){
                mqttMessageCallback.onAction(ActionType.CONNECT_SUCCESS,"连接成功");
            }
        }
        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            Log.i(TAG, "连接失败 ");
            reconnect(500);//连接失败，重连（可关闭服务器进行模拟）
            if(mqttMessageCallback!=null){
                mqttMessageCallback.onAction(ActionType.CONNECT_FAIL,"连接失败,正在重连...");
            }
        }
    };

    //订阅主题的回调
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Log.i(TAG, "收到消息： " + new String(message.getPayload()));
            //收到其他客户端的消息后，响应给对方告知消息已到达或者消息有问题等
            if(mqttMessageCallback!=null){
                mqttMessageCallback.onMessageArrived(topic,message);
            }
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
            if(mqttMessageCallback!=null){
                try {
                    mqttMessageCallback.onAction(ActionType.SEND_SUCCESS,arg0.getMessage().getId()+"");
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void connectionLost(Throwable arg0) {
            Log.i(TAG, "连接断开 ");
            reconnect(500);//连接断开，重连
            if(mqttMessageCallback!=null){
                mqttMessageCallback.onAction(ActionType.CONNECT_LOST,"已断开连接");
            }
        }
    };

    private MqttMessageCallback mqttMessageCallback;

    public MqttMessageCallback getMqttMessageCallback() {
        return mqttMessageCallback;
    }

    public void setMqttMessageCallback(MqttMessageCallback mqttMessageCallback) {
        this.mqttMessageCallback = mqttMessageCallback;
    }


    public enum ActionType{
        ON_RECEIVER,//接收到数据
        CONNECT_SUCCESS,//连接成功
        CONNECT_FAIL,//连接失败
        NO_NETWORK,//无网络
        CONNECT_LOST,//断开连接
        SEND_SUCCESS //消息发送成功
    }


    public interface MqttMessageCallback{
        /**
         * 收到消息
         * @param topic
         * @param mqttMessage
         */
        void onMessageArrived(String topic,MqttMessage mqttMessage);

        /**
         *  动作
         * @param status 动作类型
         * @param msg  提示信息
         */
        void onAction(ActionType status,String msg);
    }


    /**
     * 发布信息
     * @param topic
     * @param message
     */
    public void publish(String topic,String message) {
        LogUtil.d("mqtt.publish",topic,message);
        if(!mqttAndroidClient.isConnected()){
            LogUtil.e("mqtt.publish->error width not connected.",topic,message);
            return;
        }
        Integer qos = 2;
        Boolean retained = false;
        try {
            //参数分别为：主题、消息的字节数组、服务质量、是否在服务器保留断开连接后的最后一条消息
            mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     *  订阅主题
     * @param topic
     */
    public void subscribe(String topic){
        LogUtil.d("mqtt.subscribe",topic);
        if(!mqttAndroidClient.isConnected()){
            LogUtil.e("mqtt.subscribe->error width not connected.",topic);
            return;
        }
        try {
            mqttAndroidClient.subscribe(topic, 2);//订阅主题，参数：主题、服务质量
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消订阅主题
     * @param topic
     */
    public void unsubscribe(String topic){
        LogUtil.d("mqtt.unsubscribe",topic);
        if(!mqttAndroidClient.isConnected()){
            LogUtil.e("mqtt.unsubscribe->error width not connected.",topic);
            return;
        }
        try {
            mqttAndroidClient.unsubscribe(topic);//取消订阅主题，参数：主题
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


}
